#!/usr/bin/env python3
"""
数据优化功能演示
展示完整的analysis.csv优化精简功能
"""

import pandas as pd
import os
from datetime import datetime
from utils import optimize_analysis_data, get_optimization_recommendation
from advanced_data_optimizer import AdvancedDataOptimizer

def demo_basic_optimization():
    """演示基础优化功能"""
    print("🚀 基础数据优化演示")
    print("=" * 60)
    
    # 查找分析文件
    analysis_files = [f for f in os.listdir('.') if f.endswith('_analysis.csv')]
    
    if not analysis_files:
        print("❌ 未找到analysis.csv文件")
        return
    
    # 选择一个文件进行演示
    demo_file = analysis_files[0]
    print(f"📁 演示文件: {demo_file}")
    
    try:
        # 加载原始数据
        df = pd.read_csv(demo_file)
        print(f"📊 原始数据: {len(df)} 行 × {len(df.columns)} 列")
        
        # 演示不同优化级别
        levels = ['minimal', 'balanced', 'comprehensive']
        
        for level in levels:
            print(f"\n🔧 优化级别: {level}")
            optimized_df = optimize_analysis_data(df, level)
            
            if not optimized_df.empty:
                compression = (1 - len(optimized_df.columns) / len(df.columns)) * 100
                print(f"   结果: {len(optimized_df)} 行 × {len(optimized_df.columns)} 列")
                print(f"   压缩率: {compression:.1f}%")
                
                # 保存演示文件
                demo_output = f"demo_{level}_{datetime.now().strftime('%H%M%S')}.csv"
                optimized_df.to_csv(demo_output, index=False, encoding='utf-8-sig')
                print(f"   保存: {demo_output}")
            else:
                print("   ❌ 优化失败")
        
    except Exception as e:
        print(f"❌ 演示失败: {e}")

def demo_advanced_strategies():
    """演示高级策略优化"""
    print(f"\n🎯 高级策略优化演示")
    print("=" * 60)
    
    # 查找分析文件
    analysis_files = [f for f in os.listdir('.') if f.endswith('_analysis.csv')]
    
    if not analysis_files:
        print("❌ 未找到analysis.csv文件")
        return
    
    demo_file = analysis_files[0]
    print(f"📁 演示文件: {demo_file}")
    
    try:
        df = pd.read_csv(demo_file)
        optimizer = AdvancedDataOptimizer()
        
        print(f"📊 原始数据: {len(df)} 行 × {len(df.columns)} 列")
        
        # 获取智能推荐
        from utils import get_optimization_recommendation
        recommended_level, reason = get_optimization_recommendation(df)
        print(f"🤖 智能推荐: {recommended_level}")
        print(f"   推荐理由: {reason}")
        
        # 演示所有策略
        strategies = optimizer.get_strategy_info()
        print(f"\n📋 策略对比:")
        print("-" * 60)
        
        for strategy_key, strategy_info in strategies.items():
            try:
                optimized_df = optimizer.optimize_with_strategy(df, strategy_key)
                compression = (1 - len(optimized_df.columns) / len(df.columns)) * 100
                
                print(f"{strategy_info['name']:12} | {len(optimized_df.columns):2d}列 | {compression:5.1f}% | {strategy_info['description']}")
                
                # 保存策略演示文件
                demo_output = f"demo_{strategy_key}_{datetime.now().strftime('%H%M%S')}.csv"
                optimized_df.to_csv(demo_output, index=False, encoding='utf-8-sig')
                
            except Exception as e:
                print(f"{strategy_info['name']:12} | 失败 | {e}")
        
    except Exception as e:
        print(f"❌ 演示失败: {e}")

def demo_file_size_comparison():
    """演示文件大小对比"""
    print(f"\n📏 文件大小对比演示")
    print("=" * 60)
    
    # 查找所有相关文件
    all_files = []
    
    # 原始分析文件
    for f in os.listdir('.'):
        if f.endswith('_analysis.csv'):
            all_files.append(('原始分析', f))
    
    # 优化后文件
    for f in os.listdir('.'):
        if 'optimized' in f and f.endswith('.csv'):
            all_files.append(('优化后', f))
        elif f.startswith('demo_') and f.endswith('.csv'):
            all_files.append(('演示文件', f))
    
    if not all_files:
        print("❌ 未找到相关文件")
        return
    
    print(f"📊 文件大小对比:")
    print("-" * 80)
    print(f"{'类型':10} | {'文件名':40} | {'大小(KB)':10} | {'行数':6} | {'列数':6}")
    print("-" * 80)
    
    total_original_size = 0
    total_optimized_size = 0
    
    for file_type, filename in sorted(all_files):
        try:
            # 获取文件大小
            file_size = os.path.getsize(filename) / 1024  # KB
            
            # 获取数据维度
            df = pd.read_csv(filename)
            rows, cols = df.shape
            
            print(f"{file_type:10} | {filename:40} | {file_size:8.1f} | {rows:6d} | {cols:6d}")
            
            if file_type == '原始分析':
                total_original_size += file_size
            elif file_type in ['优化后', '演示文件']:
                total_optimized_size += file_size
                
        except Exception as e:
            print(f"{file_type:10} | {filename:40} | 错误: {e}")
    
    print("-" * 80)
    if total_original_size > 0 and total_optimized_size > 0:
        savings = total_original_size - total_optimized_size
        savings_pct = (savings / total_original_size) * 100
        print(f"💾 存储节省: {savings:.1f} KB ({savings_pct:.1f}%)")

def demo_practical_usage():
    """演示实际使用场景"""
    print(f"\n💼 实际使用场景演示")
    print("=" * 60)
    
    scenarios = [
        {
            'name': '日常交易决策',
            'strategy': 'trading_focused',
            'description': '保留交易信号、风险管理等关键信息'
        },
        {
            'name': '技术分析研究',
            'strategy': 'technical_analysis', 
            'description': '保留完整的技术指标体系'
        },
        {
            'name': '风险控制管理',
            'strategy': 'risk_management',
            'description': '专注风险评估和仓位管理'
        },
        {
            'name': '资金流向分析',
            'strategy': 'volume_analysis',
            'description': '专注成交量和资金流分析'
        }
    ]
    
    # 查找分析文件
    analysis_files = [f for f in os.listdir('.') if f.endswith('_analysis.csv')]
    
    if not analysis_files:
        print("❌ 未找到analysis.csv文件")
        return
    
    demo_file = analysis_files[0]
    
    try:
        df = pd.read_csv(demo_file)
        optimizer = AdvancedDataOptimizer()
        
        print(f"📁 演示文件: {demo_file}")
        print(f"📊 原始数据: {len(df)} 行 × {len(df.columns)} 列")
        print()
        
        for scenario in scenarios:
            print(f"🎯 场景: {scenario['name']}")
            print(f"   策略: {scenario['strategy']}")
            print(f"   说明: {scenario['description']}")
            
            try:
                optimized_df = optimizer.optimize_with_strategy(df, scenario['strategy'])
                compression = (1 - len(optimized_df.columns) / len(df.columns)) * 100
                
                print(f"   结果: {len(optimized_df)} 行 × {len(optimized_df.columns)} 列 (压缩 {compression:.1f}%)")
                
                # 显示保留的关键列
                key_columns = optimized_df.columns[:8].tolist()
                if len(optimized_df.columns) > 8:
                    key_columns.append('...')
                print(f"   关键列: {', '.join(key_columns)}")
                
            except Exception as e:
                print(f"   ❌ 失败: {e}")
            
            print()
        
    except Exception as e:
        print(f"❌ 演示失败: {e}")

def main():
    """主演示函数"""
    print("🎉 Analysis.csv数据优化精简功能演示")
    print("=" * 80)
    print("本演示将展示完整的数据优化功能，包括:")
    print("• 基础优化功能 (minimal/balanced/comprehensive)")
    print("• 高级策略优化 (5种专业策略)")
    print("• 文件大小对比")
    print("• 实际使用场景")
    print("=" * 80)
    
    # 运行所有演示
    demo_basic_optimization()
    demo_advanced_strategies()
    demo_file_size_comparison()
    demo_practical_usage()
    
    print("\n" + "=" * 80)
    print("🎊 演示完成！")
    print("💡 提示:")
    print("• 使用 'python optimize_analysis_data.py batch balanced' 批量优化")
    print("• 使用 'python advanced_data_optimizer.py' 启动高级优化工具")
    print("• 根据实际需求选择合适的优化策略")
    print("=" * 80)

if __name__ == "__main__":
    main()
